package com.luoshenshen.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * @author ShenshenLuo
 * @date 2025/3/28 22:38
 **/
public class HttpHandler extends SimpleChannelInboundHandler<HttpObject> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        if (msg instanceof HttpRequest req){
            System.out.println("req 地址 = " + req.uri());
            System.out.println("req 方法 = " + req.method());
            System.out.println("req 请求头 = " + req.headers());

            ByteBuf byteBuf = Unpooled.copiedBuffer("hello browser, i am netty http server", CharsetUtil.UTF_8);

            DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
            defaultFullHttpResponse.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");
            defaultFullHttpResponse.headers().set(HttpHeaders.Names.CONTENT_LENGTH, byteBuf.readableBytes());
            defaultFullHttpResponse.content().writeBytes(byteBuf);
            ctx.writeAndFlush(defaultFullHttpResponse);
        }
    }
}
